//获取应用实例
var app = getApp()
var config = require('../../../config.js')
var socketTask;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowPrapared: false,
    currStatus: "",
    isShow: false,
    isClose: true,
    slaveUserFace: '../../../image/default_head.png',
    slaveUserNickName: "等待配对"
  },
  toIndex: function (e) {

    if (socketTask && app.globalData.socketOpen) {
      socketTask.close({
        success: function (res) {
          console.log("socket连接关闭成功");
        }

      });
    }

    wx.redirectTo({
      url: '../competition/competition',
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;
    this.setData({
      userFaceUrl: app.globalData.userInfo.avatarUrl,
      nickName: app.globalData.userInfo.nickName

    });

    try {
      var roomID = wx.getStorageSync(config.roomId);
      console.log("当前房间的rooId是" + roomID);
      if (roomID) {
        this.setData({
          roomId: roomID
        });
      }
    } catch (e) {
    }

    //=============建立 web socket 连接================================

    socketTask = app.globalData.mSocketTask;
    if (!socketTask || !app.globalData.socketOpen) {
      app.connectSocket();
      socketTask = app.globalData.mSocketTask;
      socketTask.onOpen(function (res) {
        console.log("options.pageId == " + options.pageId);
        console.log('WebSocket连接已打开！')
        app.globalData.socketOpen = true
        //被邀请者进入房间
        console.log("您进入了擂台界面");
        if (app.globalData.socketOpen) {
          //链接已经打开  这时需要加入房间
          var msg = {
            openId: app.globalData.openid,
            type: 2,
            roomNumber: that.data.roomId
          }
          if (typeof (msg) === 'object') {
            msg = JSON.stringify(msg);
          }
          socketTask.send({
            data: msg,
            success: function () {
              console.log("重新连接 发送进入房间请求成功");
            }
          });

        }


      });
    } else {
      if (app.globalData.socketOpen) {
        //链接已经打开  这时需要加入房间
        var msg = {
          openId: app.globalData.openid,
          type: 2,
          roomNumber: that.data.roomId
        }
        if (typeof (msg) === 'object') {
          msg = JSON.stringify(msg);
        }
        socketTask.send({
          data: msg,
          success: function () {
            console.log("链接已经打开 发送进入房间请求成功");
          }
        });
      }

    }

    socketTask.onError(function (res) {
      console.log('WebSocket连接打开失败，请检查！' + res.data)
    })
    socketTask.onClose(function (res) {
      app.globalData.socketOpen = false
      console.log('WebSocket 已关闭！')
      if (that.data.isShow) {
        console.log('WebSocket 已关闭！222222222')
        wx.navigateBack({
          delta: -1
        })
      }

    });
    socketTask.onMessage(function (res) {
      // console.log('invitefriend页面收到服务器内容：' + res.data)
      var response = JSON.parse(res.data);
      if (response.type == 2) {
        if (response.success == 0) {
          //type = 2  加入房间 成功
          var resObj = response.data;
          if (resObj.masterOpenId == app.globalData.openid) {
            //我是房主 设置受邀者信息
            if (resObj.slaveUser) {
              that.setData({
                slaveUserFace: resObj.slaveUser.avatarUrl,
                slaveUserNickName: resObj.slaveUser.nickname,
                currStatus: "等待对方加入房间..."
              });
            }


          } else {
            //如果是受邀者  设置房主信息
            console.log("房主头像地址==" + resObj.masterUser.avatarUrl);
            that.setData({
              slaveUserFace: resObj.masterUser.avatarUrl,
              slaveUserNickName: resObj.masterUser.nickname,
              //受邀者进来显示 准备按钮
              isShowPrapared: true,
              currStatus: "等待对方加入房间..."
            });

          }

        } else {
          //加入房间失败
          wx.showModal({
            title: '提示',
            content: response.msg,
            success: function (res) {
              //返回上一页
              wx.navigateBack({
                delta: -1
              })
            }
          })

        }

      }

      //============准备阶段======================
      if (response.type == 3) {
        if (response.success == 0) {
          //双方都加入房间
          console.log("双方都加入房间 显示准备按钮")
          that.setData({
            isShowPrapared: true,
            currStatus: "请点击准备按钮，开始游戏..."
          });

          var resObj = response.data;
          wx.setStorageSync(config.currRoomInfo, resObj);
          if (resObj.masterOpenId == app.globalData.openid) {
            //我是房主 设置受邀者信息
            if (resObj.slaveUser) {
              that.setData({
                slaveUserFace: resObj.slaveUser.avatarUrl,
                slaveUserNickName: resObj.slaveUser.nickname
              });
            }


          } else {
            //如果是受邀者  设置房主信息
            console.log("房主头像地址==" + resObj.masterUser.avatarUrl);
            that.setData({
              slaveUserFace: resObj.masterUser.avatarUrl,
              slaveUserNickName: resObj.masterUser.nickname
            });
          }


        }
      }

      if (response.type == 5) {
        //接收到服务器通知  可以开始游戏
        if (response.success == 0) {
          //把本次全部答题存储起来
          var resObj = response.data;
          that.setData({
            isClose: false,
            currStatus: "开始游戏..."
          });
          wx.setStorageSync(config.questionList, resObj.questionVos);
          wx.redirectTo({
            url: '../battle/battle',
          })
        }
      }

      // ==========退出 进行中的游戏 =============
      if (response.type == 11) {

        if (response.success == 0) {
          //type = 2  加入房间 成功
          var resObj = response.data;
          if (resObj.masterOpenId == app.globalData.openid) {
            //受邀者退出 继续等待 
            wx.showModal({
              title: '提示',
              content: response.msg+"",
              success: function (res) {
                //返回上一页
                wx.navigateBack({
                  delta: -1
                })
              }
            })

          } else {
            //房主退出 直接退出房间
            wx.showModal({
              title: '提示',
              content: response.msg+"",
              success: function (res) {
                //返回上一页
                wx.navigateBack({
                  delta: -1
                })
              }
            })

          }
        }

      }




    });


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      isShow: true,
    });
  },


  /**
   * 通知服务器 准备好了
   */
  canPlay: function () {
    var that = this;
    if (app.globalData.socketOpen) {
      //链接已经打开    
      var msg = {
        openId: app.globalData.openid,
        type: 4,
        roomNumber: this.data.roomId
      }
      if (typeof (msg) === 'object') {
        msg = JSON.stringify(msg);
      }
      console.log("客服端确定准备状态，准备开始游戏" + msg);
      socketTask.send({
        data: msg,
        success: function (res) {
          console.log("发送确认状态成功");
          that.setData({
            currStatus: "等待对方确认..."
          });
        }
      });


    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '我在法加擂台赛挑战，没有对手，欢迎来战！',
      path: '/pages/index/index?pageId=' + config.competition + '&roomId=' + that.data.roomId,
      success: function (res) {
      }
    }

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },


  /**
 * 生命周期函数--监听页面卸载
 */
  onUnload: function () {
    //退出时 结束socket链接
    if (this.data.isClose){
      //退出时 结束socket链接
      if (socketTask && app.globalData.socketOpen) {
        socketTask.close({
          success: function (res) {
            console.log("socket连接关闭成功");
          }

        });
      }
    }

    this.setData({
      isShow: false,
    });

  },


})